<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="./general-styles-of-descendant-components.css"
    />
  </head>
  <body>
    <div id="root"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.1/umd/react.development.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.1/umd/react-dom.development.min.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
      const { Component, Fragment } = React;

      class Parent extends Component {
        state = {
          hasError: null,
        };
        /**当parent子组件会触发调用,并携带错误信息
         * 自己的不行,必须是后代的,只能捕获生命周期产生的错误
         */
        static getDerivedStateFromError(error) {
          console.log(error);
          return { hasError: error };
        }
        componentDidCatch(error, info) {
          console.log(error, info);
          console.log("这里可以请求服务端,告诉服务端错误几次,统计错误次数!!");
        }
        render() {
          return (
            <div className="Parent">
              <h3>你好react</h3>
              {this.state.hasError ? (
                <h2 className="Child" style={{ color: "white" }}>
                  当前网络不稳定,请稍后再试
                </h2>
              ) : (
                <Child />
              )}
            </div>
          );
        }
      }
      class Child extends Component {
        state = {
          users: "",
          // users: [
          //   { id: 1, name: "wxs1", age: 19 },
          //   { id: 2, name: "wxs2", age: 20 },
          //   { id: 3, name: "wxs3", age: 30 },
          //   { id: 4, name: "wxs4", age: 42 },
          // ],
        };
        render() {
          return (
            <div className="Child">
              <h3>我是child组件</h3>
              {this.state.users.map((item, index) => {
                return (
                  <h4
                    key={index}
                    style={{
                      background: "yellow",
                      padding: "0px",
                      margin: "1px 0px 0px 0px",
                    }}
                  >
                    {item.id}-{item.name}-{item.age}
                  </h4>
                );
              })}
            </div>
          );
        }
      }

      let App = (
        <Fragment>
          <Parent />
        </Fragment>
      );
      ReactDOM.render(App, document.getElementById("root"));
    </script>
  </body>
</html>
